package com.cyh.job.web;

import com.cyh.job.entity.QuartzEntity;
import com.cyh.job.entity.ReturnPage;
import com.cyh.job.service.JobService;
import com.cyh.job.utils.Result;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class JobController {

    @Autowired
    private JobService jobService;

    private static final Logger logger = LoggerFactory.getLogger(JobController.class);

    @Autowired
    private Scheduler scheduler;

    /**
     *保存任务
     * @param quartzEntity
     * @return
     */
    @RequestMapping("/saveOrUpdate")
    public Result saveOrUpdate(QuartzEntity quartzEntity, boolean isAdd){
        try {
            jobService.saveOrUpdateJob(quartzEntity, isAdd);
            return Result.success("保存成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("保存失败");
        }
    }

    /**
     * 获取列表
     * @return
     */
    @RequestMapping("/getList")
    public Result getList(QuartzEntity quartzEntity){
        ReturnPage<QuartzEntity> page = jobService.findJobList(quartzEntity);
        return Result.success(page);
    }

    /**
     * 移除这个job的触发器
     * @return
     */
    @RequestMapping("/delete")
    public String delete(QuartzEntity quartzEntity){
        jobService.delete(quartzEntity);
        return "";
    }
    
    @RequestMapping("/trigger")
    public Result fun(QuartzEntity quartzEntity){
        try {
            JobKey jobKey = new JobKey(quartzEntity.getJobName(), quartzEntity.getJobGroup());
            scheduler.triggerJob(jobKey);
            return Result.success("触发成功");
        } catch (Exception e) {
            logger.info("----------------------------job触发失败");
            e.printStackTrace();
            return Result.fail("触发失败");
        }
    }

    /**
     * 暂停job
     * @param quartzEntity
     * @return
     */
    @RequestMapping("/pauseOrResume")
    public Result pause(QuartzEntity quartzEntity) {
        try{
            TriggerKey key = new TriggerKey(quartzEntity.getTriggerName(), quartzEntity.getTriggerGroup());
            if (quartzEntity.getTriggerState().equals("PAUSED")){
                scheduler.resumeTrigger(key);
                return Result.success("恢复成功");
            }else if(quartzEntity.getTriggerState().equals("ACQUIRED")){
                scheduler.pauseTrigger(key);
                return Result.success("停止成功");
            }else{
                return Result.fail("请勿操作");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("执行失败");
        }
    }

}
